package com.clean.notification.app

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.util.Log
import com.blankj.utilcode.util.SPUtils
import com.clean.notification.BuildConfig
import com.clean.notification.device.LTRepositoryPhone
import com.clean.notification.net.SerializationConverter
import com.clean.notification.noti.NotifyShowUtils
import com.clean.notification.receiver.ScreenListener
import com.clean.notification.receiver.ScreenListener.ScreenStateListener
import com.drake.net.NetConfig
import com.drake.net.interceptor.LogRecordInterceptor
import com.drake.net.okhttp.setConverter
import com.drake.net.okhttp.setDebug
import java.util.concurrent.TimeUnit


open abstract class BaseApplication : Application() {
    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var mContext: Context
        var fcmUrl = ""
        var fcmPort = ""
    }

    private lateinit var screenListener: ScreenListener

    override fun onCreate() {
        super.onCreate()
        mContext = this

        fcmUrl = initFcmUrl()
        fcmPort = initFcmPort()
        LTRepositoryPhone.init(this, getAppName());
        LifecycleMonitor.instance?.register(this)
        NetConfig.initialize(fcmUrl, this) {
            // 超时设置
            connectTimeout(30, TimeUnit.SECONDS)
            readTimeout(30, TimeUnit.SECONDS)
            writeTimeout(30, TimeUnit.SECONDS)
            // 本框架支持Http缓存协议和强制缓存模式
//            cache(Cache(cacheDir, 1024 * 1024 * 128)) // 缓存设置, 当超过maxSize最大值会根据最近最少使用算法清除缓存来限制缓存大小
            // LogCat是否输出异常日志, 异常日志可以快速定位网络请求错误
            setDebug(BuildConfig.DEBUG)
            // AndroidStudio OkHttp Profiler 插件输出网络日志
            addInterceptor(LogRecordInterceptor(BuildConfig.DEBUG))
//            setErrorHandler(object : NetErrorHandler {
//                override fun onError(e: Throwable) {
//                    Log.e("aaa", "onError: 发送错误 -- ${e.printStackTrace()}" )
//                    Log.e("aaa", "onError: 发送错误 -- ${e.message}" )
//                }
//            })
            setConverter(SerializationConverter())
        }
        SPUtils.getInstance().put("isForeground", true)
        screenListener = ScreenListener(this)
        screenListener.begin(object : ScreenStateListener {
            override fun onScreenOn() {
                Log.e("aaa", "onScreenOn: 屏幕 打开 了 ~")
                NotifyShowUtils.tryShowLocalPush()
            }

            override fun onScreenOff() {
                Log.e("aaa", "onScreenOn: 屏幕 关闭 了 ~")
            }

            override fun onUserPresent() {
                Log.e("aaa", "onScreenOn: 屏幕 解锁 了 ~")
                NotifyShowUtils.tryShowLocalPush()
            }

        })
    }

    abstract fun getAppName(): String

    abstract fun initFcmPort(): String

    abstract fun initFcmUrl(): String

}